<template>
  <el-tabs
    v-model="data.activeTab"
    class="demo-tabs"
    @tab-click="handleClickTab"
  >
    <el-tab-pane label="流水记录" name="flow">
      <Table
        v-if="data.activeTab === 'flow'"
        ref="tableRef"
        :columns="data.columns"
        :toolbar="data.toolbar"
        :query="data.query"
        :othercontent="true"
        @get-list="getData"
      >
        <template #othercontent>
          <div class="card">
            <div class="icon-top"></div>
            <div class="card-content com-head-wrap1">
              <div class="card-data">
                <div class="card-item">
                  <!-- <div class="iconfont icon-charging-capacity"></div> -->
                  <div class="right">
                    <div class="title">总计（元）</div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-charging-capacity"></div> -->
                  <div class="right">
                    <div class="title">个人充值</div>
                    <div class="title">
                      {{
                        data.detailData?.cashRecharge
                          ? formatNumber(data.detailData.cashRecharge)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-electricity-fee"></div> -->
                  <div class="right">
                    <div class="title">个人退款</div>
                    <div class="title">
                      {{
                        data.detailData?.cashRefund
                          ? formatNumber(data.detailData.cashRefund)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-service-fee"></div> -->
                  <div class="right">
                    <div class="title">余额修正</div>
                    <div class="title">
                      {{
                        data.detailData.platformUpdate
                          ? formatNumber(data.detailData.platformUpdate)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-dividend"></div> -->
                  <div class="right">
                    <div class="title">充电消费</div>
                    <div class="title">
                      {{
                        data.detailData?.chargeConsume
                          ? formatNumber(data.detailData.chargeConsume)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <div class="right">
                    <div class="title">超时占用消费</div>
                    <div class="title">
                      {{
                        data.detailData?.occupyRecharge
                          ? formatNumber(data.detailData.occupyRecharge)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-dividend"></div> -->
                  <div class="right">
                    <div class="title">资金下发</div>
                    <div class="title">
                      {{
                        data.detailData?.issueFund
                          ? formatNumber(data.detailData.issueFund)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-item">
                  <!-- <div class="iconfont icon-dividend"></div> -->
                  <div class="right">
                    <div class="title">资金扣回</div>
                    <div class="title">
                      {{
                        data.detailData?.recycleFund
                          ? formatNumber(data.detailData.recycleFund)
                          : '--'
                      }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="icon-bottom"></div>
          </div>
        </template>
      </Table>
    </el-tab-pane>
    <el-tab-pane label="微信消费对账" name="wx">
      <Table
        v-if="data.activeTab === 'wx'"
        ref="tableWxRef"
        :columns="wxData.columns"
        :toolbar="wxData.toolbar"
        :query="wxData.query"
        @get-list="getWxData"
      ></Table
    ></el-tab-pane>
    <el-tab-pane label="用户账户余额" name="account">
      <Table
        v-if="data.activeTab === 'account'"
        ref="tableAccountRef"
        :columns="accountData.columns"
        :handles="accountData.handles"
        :query="accountData.query"
        @get-list="getAccountData"
      ></Table
    ></el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup name="channelReconciliationList">
import Table from '@/components/table/index.vue';
import moment from 'moment';
import { queryDicByParent } from '@/service/apis/api';
import {
  URL_PAGINGALLACCOUNTFLOW,
  getAllAccountFlowTotal,
  pagingAllAccountFlow,
  pagingConsumerInvoice,
  pagingAccountPeriodTotal,
  EXPORT_ALLACCOUNTFLOW,
  EXPORT_CONSUMERINVOICE,
  EXPORT_ACCOUNTPERIOD,
} from '@/service/apis/financial';
import { formatNumber, exportFile } from '@/utils/utils';

const router = useRouter();

const tableRef = ref();
const tableWxRef = ref();
const tableAccountRef = ref();

const data = reactive({
  pickDate: null as any,
  activeTab: 'flow',
  detailData: {} as any,
  columns: [
    {
      prop: 'billId',
      label: '流水号',
    },
    {
      prop: 'accountNumber',
      label: '用户账号',
    },
    {
      prop: 'userOrgName',
      label: '归属企业',
    },
    {
      prop: 'orderId',
      label: '关联订单(充电/支付)',
    },
    {
      prop: 'type',
      label: '流水类型',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'paymentType',
      label: '支付钱包',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'amount',
      label: '流水金额',
    },
    {
      prop: 'createTime',
      label: '流水时间 ',
    },
    {
      prop: 'remark',
      label: '备注 ',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: 'channelReconciliationList.export',
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      // handle: (row: any) => {
      //   exportFile(
      //     EXPORT_ALLACCOUNTFLOW,
      //     '流水记录',
      //     tableRef.value?.getForm()
      //   );
      // },
      handle: (row: any) => {
        const startData = tableRef?.value.getForm().startTime;
        const startData1 = tableRef?.value.getForm().endTime;
        const day = moment(startData1).diff(moment(startData), 'day');
        if ((startData || day > 0) && day < 63) {
          exportFile(
            EXPORT_ALLACCOUNTFLOW,
            '流水记录',
            tableRef.value?.getForm()
          );
        } else {
          ElMessageBox.alert(
            '单次导出最多支持导出周期为2个月的数据，请按时间筛选导出对象后再导出。',
            '提示',
            {
              confirmButtonText: '确认',
              type: 'warning',
            }
          );
        }
      },
    },
  ],
  query: [
    {
      label: '流水时间',
      prop: 'data',
      comName: 'date',
      keys: ['startTime', 'endTime'],
      props: {
        type: 'daterange',
        calendarChange: (pick: any) => {
          let hasSelectDate = pick !== null && pick.length > 0;
          data.pickDate = hasSelectDate ? pick[0] : null;
        },
        change: (time: any) => {
          if (!time) {
            data.pickDate = null;
          }
        },
        disabledDate: (time: any): any => {
          if (data.pickDate) {
            const checkTime = data.pickDate.getTime();
            const startTime = checkTime - 62 * 86400 * 1000; // 前面限制62天
            const endTime = checkTime + 62 * 86400 * 1000; // 后面限制62天
            return time.getTime() > endTime || time.getTime() < startTime;
          } else {
            return false;
          }
        },
      },
    },
    {
      label: '流水类型',
      prop: 'type',
      comName: 'select',
      props: {
        placeholder: '请选择流水类型',
        options: [] as any,
      },
    },
    {
      label: '归属企业',
      prop: 'userOrgName',
      comName: 'input',
      props: {
        placeholder: '请输入归属企业',
      },
    },
    {
      label: '用户账号',
      prop: 'accountNumber',
      comName: 'input',
      props: {
        placeholder: '请输入用户账号',
      },
    },
    {
      label: '关联订单号',
      prop: 'orderId',
      comName: 'input',
      props: {
        placeholder: '请输入关联订单号',
      },
    },
    {
      label: '手机号',
      prop: 'mobile',
      comName: 'input',
      props: {
        placeholder: '请输入用户手机号',
      },
    },
  ],
});
const wxData = reactive({
  columns: [
    {
      prop: 'accountNumber',
      label: '用户账号',
    },
    {
      prop: 'type',
      label: '消费类型',
      dic: [] as any,
      type: Number,
    },
    {
      prop: 'orderId',
      label: '订单号',
    },
    {
      prop: 'userOrgName',
      label: '归属企业',
    },
    {
      prop: 'totalAmount',
      label: '订单总金额（优惠前）',
    },
    {
      prop: 'powerAmount',
      label: '实收电费（微信）',
    },
    {
      prop: 'serviceAmount',
      label: '实收服务费（微信）',
    },
    {
      prop: 'amount',
      label: '实收总金额（微信）',
    },
    {
      prop: 'orderOrgName',
      label: '运营商',
    },
    {
      prop: 'createTime',
      label: '支付时间',
    },
  ],
  toolbar: [
    {
      label: '导出',
      permission: 'channelReconciliationList.export',
      icon: 'icon-export',
      type: 'primary',
      plain: true,
      handle: (row: any) => {
        exportFile(
          EXPORT_CONSUMERINVOICE,
          '微信消费对账',
          tableWxRef.value?.getForm()
        );
      },
    },
  ],
  query: [
    {
      label: '统计日期',
      prop: 'data',
      comName: 'date',
      keys: ['startTime', 'endTime'],
      props: {
        type: 'daterange',
      },
    },
  ],
});
const accountData = reactive({
  columns: [
    {
      prop: 'period',
      label: '月份',
    },
    {
      prop: 'wechatBalance',
      label: '微信结转',
    },
    {
      prop: 'unitBalance',
      label: '企业钱包结转',
    },
  ],
  handles: [
    {
      label: '查看明细',
      permission: 'channelReconciliationList.see',
      handle: (row: any) => {
        console.log('查看明细---', row);
        router.push({
          name: 'accountBalanceDetail',
          query: { period: row.period },
        });
      },
    },
    {
      label: '导出明细',
      permission: 'channelReconciliationList.export',
      handle: (row: any) => {
        console.log('导出明细---', row);
        exportFile(EXPORT_ACCOUNTPERIOD, '用户账户余额', {
          period: row.period,
        });
      },
    },
  ],
  query: [
    {
      label: '选择月份',
      prop: 'period',
      comName: 'date',
      props: {
        placeholder: '请选择月份',
        type: 'month',
      },
    },
  ],
});

const startDate = moment()
  .subtract(1, 'month')
  .startOf('month')
  .format('YYYY-MM-DD');
const endDate = moment()
  .subtract(1, 'month')
  .endOf('month')
  .format('YYYY-MM-DD');
console.log(startDate, endDate);

// 字典取值
queryDicByParent({
  listDtos: ['accountFlowType', 'paymentType', 'accountFlowType'],
}).then((res: any) => {
  if (res) {
    data.query[1].props.options = [...res.accountFlowType];
    data.columns[4].dic = [...res.accountFlowType];
    data.columns[5].dic = [...res.paymentType];
    wxData.columns[1].dic = [...res.accountFlowType];
  }
});

// 获取流水记录
const getData = (page: any, search: any) => {
  nextTick(() => {
    let form: any = search.ruleForm;
    if (!form.data) {
      form.data = [startDate, endDate];
    }
    if (form.data && form.data.length > 0) {
      form.startTime = form.data[0];
      form.endTime = form.data[1];
    } else {
      form.startTime = '';
      form.endTime = '';
    }
    form.channelType = 0;
    pagingAllAccountFlow(form, page).then((res: any) => {
      if (res) {
        if (
          page.pageNo !== 1 &&
          (!res.dataList || res.dataList?.length === 0)
        ) {
          page.pageNo--;
          getData(page, search);
          return;
        }
        nextTick(() => {
          tableRef.value.setTable({
            total: res.totalCount,
            table: res.dataList,
          });
        });
      }
    });
    getAllAccountFlowTotal(form, page).then((res: any) => {
      if (res) {
        data.detailData = res;
      } else {
        data.detailData = {};
      }
    });
  });
};

// 微信消费对账
const getWxData = (page: any, search: any) => {
  nextTick(() => {
    let form: any = search.ruleForm;
    if (!form.data) {
      form.data = [startDate, endDate];
    }
    if (form.data && form.data.length > 0) {
      form.startTime = form.data[0];
      form.endTime = form.data[1];
    }
    form.channelType = 1;
    pagingConsumerInvoice(form, page).then((res: any) => {
      if (res) {
        if (
          page.pageNo !== 1 &&
          (!res.dataList || res.dataList?.length === 0)
        ) {
          page.pageNo--;
          getWxData(page, search);
          return;
        }
        nextTick(() => {
          tableWxRef.value.setTable({
            total: res.totalCount,
            table: res.dataList,
          });
        });
      }
    });
  });
};

// 用户账户余额
const getAccountData = (page: any, search: any) => {
  nextTick(() => {
    let form: any = search.ruleForm;
    pagingAccountPeriodTotal(form, page).then((res: any) => {
      if (res) {
        if (
          page.pageNo !== 1 &&
          (!res.dataList || res.dataList?.length === 0)
        ) {
          page.pageNo--;
          getAccountData(page, search);
          return;
        }
        nextTick(() => {
          tableAccountRef.value.setTable({
            total: res.totalCount,
            table: res.dataList,
          });
        });
      }
    });
  });
};

const handleClickTab = (e: any) => {};
</script>
<style lang="scss" scoped>
@import '@/assets/styles/head.scss';
.card {
  padding: 30px 0;
  .card-content {
    width: 100%;
    .card-data {
      .card-item {
        display: flex;
        .title {
          margin-left: 12px;
        }
        .iconfont {
          font-size: 56px;
        }
      }
    }
  }
}
</style>